package ltd.newbee.mall.advice;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.config.RsaKey;
import ltd.newbee.mall.config.annotation.Encrypt;
import ltd.newbee.mall.util.CryptoUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Objects;

@ControllerAdvice
@Slf4j
@Order(2)
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Resource
    private RsaKey rsaKey;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(Encrypt.class);
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("相应数据 bodyWrite = {}", body);
        if (supports(returnType, selectedConverterType)) {
            // 转对象jsonStr
            String data = JSONObject.toJSONString(body);
            // aes 的密文
            String key = CryptoUtils.generateSymmetricKey(CryptoUtils.Algorithm.AES_CBC_PKCS5);
            String secretData = CryptoUtils.encryptSymmetrically(key, key, data, CryptoUtils.Algorithm.AES_CBC_PKCS5);
            long timestamp = System.currentTimeMillis() / 1000L;
//            String securityKey = CryptoUtils.encryptByRSAPrivate(rsaKey.getPrivateKey(), key);
            String signature = DigestUtil.md5Hex(timestamp + key + secretData);
            return new RespSecretData(timestamp, signature, key, secretData, 200);
        }
        return body;
    }
}
